import numpy as np
import cv2
from fastapi import FastAPI, WebSocket,HTTPException
from fastapi.responses import HTMLResponse, JSONResponse, FileResponse, StreamingResponse
import uvicorn
import json
import asyncio
import threading
import time
import traceback
from queue import Queue, Empty
# from get_datas3 import Camera, Variable
from fastapi.middleware.cors import CORSMiddleware
import os
import psutil
import orjson
from pydantic import BaseModel
cv2.setNumThreads(4)

app = FastAPI()
# 添加 CORS 中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 允许所有来源
    allow_credentials=True,
    allow_methods=["*"],  # 允许所有 HTTP 方法
    allow_headers=["*"],  # 允许所有 HTTP 头
)

class get_Datas(BaseModel):
    data_2d: dict
    data_3d: dict  

# camera = Camera()
latest_data = {
    "data_2d": None,
    "data_3d": None,
}



@app.post("/get_data")
async def receive_data(result: get_Datas):
    if not (isinstance(result.data_2d, dict)) or not (isinstance(result.data_3d, dict)):
        raise HTTPException(status_code=400, detail="Invalid data format")
    
    # 更新全局数据
    latest_data.update({
        "data_2d": result.data_2d,
        "data_3d": result.data_3d,
    })
    
    return {"status": "success", "message": "Data received"}


@app.get("/h5_data")
async def send_to_h5():
    """向H5页面提供最新数据"""
    if latest_data["data_2d"] is None:
        raise HTTPException(status_code=404, detail="No data available")
    
    kps_dict_2d = latest_data["data_2d"]
    pts_3d_dict = latest_data["data_3d"]
    
    
    res = {
        'data_2d': kps_dict_2d,
        'data_3d': pts_3d_dict, 
    }       
    return res

split_text = b'jcznbjkeji'
def generate_data():
    """生成处理结果数据流"""
    while True:
        try:
            if latest_data["data_2d"] is not None:
                res = orjson.dumps(res) + split_text
                yield res
            else:
                raise HTTPException(status_code=404, detail="No data available")
        except Exception as e:
            print(f"Error generating data: {e}")


@app.get("/data")
async def get_data():
    """数据流接口"""
    return StreamingResponse(
        generate_data(),
        media_type="application/octet-stream"
    )






def main():
    uvicorn.run(app, host='0.0.0.0', port=8000, log_config=None)


if __name__ == '__main__':
    main()